package com.wbu.service;

import java.io.Serializable;
import java.util.*;

import javax.servlet.http.HttpSession;

import com.wbu.config.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.wbu.entity.Admin;
import com.wbu.entity.Park;
import com.wbu.mapper.AdminMapper;
import com.wbu.mapper.ParkMapper;
@Service
public class ParkService{
	
	@Autowired
	private ParkMapper parkMapper;

	@Autowired
	private RedisUtils redisUtils;
	
	public List<Park> getAll() {
		List<Park> parkList = null;
		Set<Object> listSets = redisUtils.getKeyLikePatern("parkKey:");
		if(CollectionUtils.isEmpty(listSets)){
			parkList = parkMapper.findAllPark();
			//redis没有车位信息添加到redis
			parkList.stream().forEach(parkInfo -> {
				redisUtils.set("parkKey:"+parkInfo.getId(),parkInfo);
			});
		}else {
			parkList = new ArrayList<Park>();
			for(Iterator<Object> iter = listSets.iterator();
				iter.hasNext();){
				Park p = (Park) iter.next();
				parkList.add(p);
			}
		}
		return parkList;
	}
	
	public List<Park> getAllByStatus(int status) {
		return parkMapper.findAllParkByStatus(status);
	}
	
	public List<Park> getAllByKey(String key) {
		return parkMapper.findAllParkByKey(key);
	}
	public Park getParkById(int id) {
		Park park = (Park) redisUtils.get("parkKey:"+id);
		if(park==null){
			park = parkMapper.findParkById(id);
			redisUtils.add("parkKey:"+park.getId(),park);
		}
		return park;
	}
	
	public boolean updatePark(Park park) {
		try {
			 parkMapper.updatePark(park);
			 redisUtils.remove("parkKey:"+park.getId());
			 redisUtils.set("parkKey:"+park.getId(),park);
			 return true;
		} catch (Exception e) {
			return false;
		}
	}
	public boolean updateParkStatus(int status,int parkId) {
		try {
			 parkMapper.updateParkStatus(status);
			 redisUtils.remove("parkKey:"+parkId);
			 redisUtils.set("parkKey:"+parkId,getParkById(parkId));
			 return true;
		} catch (Exception e) {
			return false;
		}
	}
	public boolean deletePark(int id) {
		
		try {
			parkMapper.deletePark(id);
			redisUtils.removePattern("parkKey:"+id);
			 return true;
		} catch (Exception e) {
			return false;
		}
	}
	
	public boolean insertPark(Park park) {
		int autoIncrementId = parkMapper.insertPark(park);
		redisUtils.set("parkKey:"+autoIncrementId,getParkById(autoIncrementId));
		return (autoIncrementId > 0)?true:false;
	}
	
}
